﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Collections;

namespace My.Utils
{
    /// <summary>
    /// 使用xml文件做为配置文件，实现了配置文件的实时读写，支持多个配置文件，以及通过磁盘修改配置文件不需要重启应用程序立即生效。
    /// </summary>
    public class XmlConfig
    {
        public static Hashtable ConfigFileList = new Hashtable();//存储所有配置文件的key值

        public DataSet DsConfig
        {
            get
            {
                return (DataSet)ConfigFileList[XmlFileName];
            }
            set
            {
                ConfigFileList[XmlFileName] = value;
            }

        }

        public string XmlFilePath;
        public string XmlFileName;

        public XmlConfig()
            : this(AppDomain.CurrentDomain.BaseDirectory + "config.xml")
        {
        }

        public XmlConfig(string path)
        {
            XmlFilePath = path;
            XmlFileName = Path.GetFileName(path);

            DsConfig = new DataSet();
            DsConfig.ReadXml(path);

            if (ConfigFileList[XmlFileName] == null)
            {
                ConfigFileList.Add(ConfigFileList, DsConfig);
            }
            System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(Path.GetDirectoryName(path), "*.xml");//文件监控类
            watcher.Changed += new System.IO.FileSystemEventHandler(watcher_Changed);
        }

        //配置文件发生改变，重新加载配置文件
        public void watcher_Changed(object o, FileSystemEventArgs args)
        {
            DsConfig = new DataSet();
            DsConfig.ReadXml(XmlFilePath);
        }

        public string GetConfig(string key, string tableName)
        {
            DataTable table = tableName == string.Empty ? DsConfig.Tables[0] : DsConfig.Tables[tableName];
            return table.Rows[0][key].ToString();

        }
        public string GetConfig(string key)
        {
            return this.GetConfig(key, string.Empty);

        }

        public void SetConfig(string key, string val, bool flush, string tableName)
        {
            DataTable table = tableName == string.Empty ? DsConfig.Tables[0] : DsConfig.Tables[tableName];
            table.Rows[0][key] = val;
            if (flush)
            {
                DsConfig.WriteXml(XmlFilePath);
            }

        }

        public void SetConfig(string key, string val, bool flush)
        {
            this.SetConfig(key, val, flush, string.Empty);
        }

        public void SetConfig(string key, string val)
        {
            this.SetConfig(key, val, true);
        }

        public void Flush()
        {
            DsConfig.WriteXml(XmlFilePath);
        }
    }
}
